﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Xml.XPath;

namespace ElkiTools.SPListCaller.Core.Extensions
{
    public static class XElementExt
    {
        public static string InnerXml(this XElement xe)
        {
            return xe.InnerXml(SaveOptions.None);
        }

        public static string InnerXml(this XElement xe, SaveOptions saveOptions)
        {
            string result = string.Empty;
            //------------------------------------------------------------------------------------


            string joinSeparator = Environment.NewLine;

            switch (saveOptions)
            {
                case SaveOptions.DisableFormatting:
                    joinSeparator = string.Empty;
                    break;
                case SaveOptions.None:
                    joinSeparator = Environment.NewLine;
                    break;
                case SaveOptions.OmitDuplicateNamespaces:
                    joinSeparator = Environment.NewLine;
                    break;
                default:
                    joinSeparator = Environment.NewLine;
                    break;
            }

            result = string.Join(joinSeparator, xe.Nodes().Select(node => node.ToString(saveOptions)).ToArray());


            //------------------------------------------------------------------------------------
            return result;
        }

        public static string GetIndentedXml(string xml)
        {
            return GetFormattedXml(xml, SaveOptions.OmitDuplicateNamespaces);
        }

        public static string GetFlatXml(string xml)
        {
            return GetFormattedXml(xml, SaveOptions.DisableFormatting);
        }

        public static string GetFormattedXml(string xml, SaveOptions saveOptions)
        {
            string result = xml;
            //------------------------------------------------------------------------------------

            try
            {
                result = XElement.Parse(xml)
                    .ToString(saveOptions);
            }
            catch
            {
                try
                {
                    result = XElement.Parse("<Dummy>" + xml + "</Dummy>")
                        .InnerXml(saveOptions);
                }
                catch
                {
                    // TODO : définir l'action à mener
                    throw;
                }
            }

            //------------------------------------------------------------------------------------
            return result;
        }
    }
}
